﻿using System;
using System.Windows;

namespace JonThomas.SpaceBounce
{
	/// <summary>
	/// A Vector class. Supports vector adding
	/// Operates in a coordinate system where x increases to the right, y increases down, 
	/// and angles are measured in radians from the top towards the right.
	/// </summary>
	public class Vector
	{
		private double m_speed;
		private double m_angle;
		private double m_x;
		private double m_y;

		/// <summary>
		/// Creates a new vector and calculates it's X and Y endpoint in relation to the origin.
		/// </summary>
		/// <param name="speed">The length of the Vector</param>
		/// <param name="angle">The angle of the Vector in radians, measured from the top towards the right</param>
		public Vector(double speed, double angle)
		{
			if (speed < 0)
			{
				throw new ArgumentException("speed must be greater or equal to zero when creating a Vector");
			}
			m_speed = speed;
			m_angle = angle;
			m_y = Math.Cos(angle) * speed * -1;
			m_x = Math.Sin(angle) * speed;
		}

		/// <summary>
		/// Creates a new vector starting in origo, ending in a Point endpoint.
		/// </summary>
		public Vector(Point endPoint)
		{
			m_x = endPoint.X;
			m_y = endPoint.Y;
			m_speed = Math.Sqrt(m_x * m_x + m_y * m_y);
			
			// Calculate angle
			if (m_x > 0 && m_y < 0) { m_angle = Math.Atan(m_x / m_y) * -1; }
			else if (m_x > 0 && m_y > 0) { m_angle = Math.Atan(m_y / m_x) + Math.PI / 2; }
			else if (m_x < 0 && m_y > 0) { m_angle = Math.Atan(m_x / m_y) * -1 + Math.PI; }
			else if (m_x < 0 && m_y < 0) { m_angle = Math.Atan(m_y / m_x) + Math.PI * 3 / 2; }
			else if (m_x == 0) { m_angle = Math.PI / 2 + Math.PI / 2 * Math.Sign(m_y); }	// Math.PI or 0
			else if (m_y == 0) { m_angle = Math.PI - Math.PI / 2 * Math.Sign(m_x); }	// Math.PI/2 or Math.PI*3/2
		}

		public double X 
		{ 
			get {return m_x; }
		}
		public double Y 
		{ 
			get { return m_y; }
		}
		public double Speed
		{
			get { return m_speed; }
		}
		/// <summary>
		/// The angle of the vector in radians
		/// </summary>
		public double Angle
		{
			get { return m_angle; }
		}

		public static Vector operator +(Vector a, Vector b)
		{
			return new Vector(new Point(a.X + b.X, a.Y + b.Y));
		}
	}
}
